<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }

        .layuimini-form .layui-form-label {
            width: 120px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>采购订单信息</legend>
            <div style="margin: 3px 3px 3px 3px">
                <form class="layui-form layuimini-form" action="">
                    <input type="text" name="purchaseOrderId" id="purchaseOrderId" style="display: none"
                           class="layui-input">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label required">订单号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="orderNo" id="orderNo"
                                       value="" autocomplete="off" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label required">供应商:</label>
                            <div class="layui-input-inline">
                                <select lay-verify="required" name="supId" id="supId" lay-search="">
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">签约日期</label>
                            <div class="layui-input-inline">
                                <input readonly="readonly" type="text" class="layui-input" name="signDate"
                                       id="signDate">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">有效起始日期</label>
                            <div class="layui-input-inline">
                                <input readonly="readonly" type="text" class="layui-input" name="validStartDate"
                                       id="validStartDate">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">有效结束日期</label>
                            <div class="layui-input-inline">
                                <input readonly="readonly" type="text" class="layui-input" name="validEndDate"
                                       id="validEndDate">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">交期计划方式</label>
                            <div class="layui-input-inline">
                                <select name="deliveryPlanType" id="deliveryPlanType">
                                    <option value="">请选择</option>
                                    <option value="FIXED_DATE">固定日期</option>
                                    <option value="BY_ORDER_RATIO">按订单比例</option>
                                    <option value="INSTALLMENT">分期</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">预计交货日期</label>
                            <div class="layui-input-inline">
                                <input readonly="readonly" type="text" class="layui-input" name="expectedDeliveryDate"
                                       id="expectedDeliveryDate">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">提货期限开始</label>
                            <div class="layui-input-inline">
                                <input readonly="readonly" type="text" class="layui-input" name="pickupPeriodStart"
                                       id="pickupPeriodStart">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">提货期限结束</label>
                            <div class="layui-input-inline">
                                <input readonly="readonly" type="text" class="layui-input" name="pickupPeriodEnd"
                                       id="pickupPeriodEnd">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">增值税税率</label>
                            <div class="layui-input-inline">
                                <input type="number" name="taxRate" id="taxRate"
                                       value="" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">订单总金额</label>
                            <div class="layui-input-inline">
                                <input type="number" name="totalAmount" id="totalAmount" disabled
                                       value="" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">不含税总金额</label>
                            <div class="layui-input-inline">
                                <input type="number" name="totalTaxFreeAmount" id="totalTaxFreeAmount" disabled
                                       value="" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">增值税金额</label>
                            <div class="layui-input-inline">
                                <input type="number" name="taxAmount" id="taxAmount" disabled
                                       value="" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <!-- 状态字段已移除，默认设置为准备状态(10) -->
                        <div class="layui-inline">
                            <label class="layui-form-label">业务来源</label>
                            <div class="layui-input-inline">
                                <select name="bizSource" id="bizSource">
                                    <option value="">请选择</option>
                                    <option value="INTERNAL">内部</option>
                                    <option value="EXTERNAL">外部</option>
                                    <option value="FRAMEWORK">框架协议</option>
                                    <option value="OTHER">其他</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">来源单据号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="sourceDocNo" id="sourceDocNo"
                                       value="" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">交期条款</label>
                        <div class="layui-input-block">
                            <textarea type="text" name="deliveryTerms" id="deliveryTerms"
                                      value="" autocomplete="off" class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">业务来源说明</label>
                        <div class="layui-input-block">
                            <textarea type="text" name="bizSourceDesc" id="bizSourceDesc"
                                      value="" autocomplete="off" class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <!-- 驳回原因显示（只在驳回状态时显示） -->
                    <div class="layui-form-item layui-form-text" id="rejectReasonDiv" style="display: none;">
                        <label class="layui-form-label">驳回原因</label>
                        <div class="layui-input-block">
                            <textarea type="text" name="attr1" id="attr1" readonly
                                      autocomplete="off" class="layui-textarea" style="background-color: #f5f5f5;"></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="save-purchase-order">
                                保存采购订单
                            </button>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn layui-btn-danger" lay-submit lay-filter="submit-purchase-order">
                                提交订单
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加明细</button>
            </div>
        </script>
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn isShow layui-btn-normal layui-btn-xs data-count-edit"  lay-event="show">查看</a>
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit"  lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete"  lay-event="delete">删除</a>
        </script>
    </div>
</div>
<script src="/static/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/static/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/static/lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>
<script src="/static/js/common.js"></script>
<script>
    let purchaseOrderId = $.common.getUrlParam("purchaseOrderId");
    let supId = $.common.getUrlParam("supId");
    let user = $.common.getUserInfo();
    let isShow =  $.common.getUrlParam("isShow");
    let orderStatus = $.common.getUrlParam("docStatus") || "10"; // 获取订单状态，默认为准备状态
    
    if (0 != user.powerDataType) {
        $('#totalAmount').attr("disabled", true);
        $('#totalTaxFreeAmount').attr("disabled", true);
        $('#taxAmount').attr("disabled", true);
    }
    
    // 根据订单状态控制编辑权限
    if (parseInt(orderStatus) >= 30) {
        // 状态大于等于30时，禁用所有输入字段
        $('input, select, textarea').attr('disabled', true);
        $('.layui-btn[lay-filter="save-purchase-order"]').hide();
        $('.layui-btn[lay-filter="submit-purchase-order"]').hide();
        $('.layui-btn[lay-event="add"]').hide(); // 隐藏添加明细按钮
        $('.layui-btn[lay-event="edit"]').hide(); // 隐藏编辑明细按钮
        $('.layui-btn[lay-event="delete"]').hide(); // 隐藏删除明细按钮
    } else if (parseInt(orderStatus) == 10) {
        // 准备状态时，显示保存和提交按钮
        $('.layui-btn[lay-filter="save-purchase-order"]').show();
        $('.layui-btn[lay-filter="submit-purchase-order"]').show();
    }
    
    // 根据状态控制驳回原因显示
    if (parseInt(orderStatus) == 11) {
        // 驳回状态时显示驳回原因
        $('#rejectReasonDiv').show();
    } else {
        // 其他状态隐藏驳回原因
        $('#rejectReasonDiv').hide();
    }
    layui.use(['form', 'laydate'], function () {
        var form = layui.form,
            laydate = layui.laydate,
            table = layui.table,
            util = layui.util,
            layer = layui.layer;
        //初始化时间
        laydate.render({
            elem: '#signDate'
            , type: 'date'
        });
        laydate.render({
            elem: '#validStartDate'
            , type: 'date'
        });
        laydate.render({
            elem: '#validEndDate'
            , type: 'date'
        });
        laydate.render({
            elem: '#expectedDeliveryDate'
            , type: 'date'
        });
        laydate.render({
            elem: '#pickupPeriodStart'
            , type: 'date'
        });
        laydate.render({
            elem: '#pickupPeriodEnd'
            , type: 'date'
        });

        //初始化下拉框 供应商
        let callback = {
            onSuccess: function (result) {
                if (result.code == '0') {
                    $('#supId').append(new Option('请选择', '', true));// 下拉菜单里添加元素
                    $.each(result.data, function (index, item) {
                        let option = new Option(item.supplierName, item.id);
                        if (supId) {
                            if (item.id == supId) {
                                option.selected = true;
                            }
                        }
                        $('#supId').append(option);// 下拉菜单里添加元素
                    });
                } else {
                    $.common.showErrorMessage(result.message)
                    return false;
                }
            }
        };
        $.xAjax('/supplier/select', 'POST', JSON.stringify({}), callback);

        //初始化下拉框
        form.render("select");
        // 设置默认状态为准备(10) - 通过隐藏字段设置
        if (!purchaseOrderId || purchaseOrderId == '') {
            // 新建订单时设置默认状态
            $('form').append('<input type="hidden" name="docStatus" value="10">');
        } else {
            // 编辑订单时，如果URL中没有状态参数，设置为准备状态
            if (!orderStatus || orderStatus == '') {
                $('form').append('<input type="hidden" name="docStatus" value="10">');
            } else {
                // 使用传递过来的状态
                $('form').append('<input type="hidden" name="docStatus" value="' + orderStatus + '">');
            }
        }

        // 监听采购订单保存
        form.on('submit(save-purchase-order)', function (data) {
            // 处理所有可能的空日期字段，将空字符串设置为当前日期
            const dateFields = ['signDate', 'validStartDate', 'validEndDate', 'expectedDeliveryDate', 
                               'pickupPeriodStart', 'pickupPeriodEnd'];
            
            // 获取当前日期，格式为 YYYY-MM-DD
            const today = new Date();
            const currentDate = today.getFullYear() + '-' + 
                              String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                              String(today.getDate()).padStart(2, '0');
            
            dateFields.forEach(function(fieldName) {
                if (!data.field[fieldName] || data.field[fieldName].trim() === '') {
                    data.field[fieldName] = currentDate;
                }
            });
            
            // 如果是新建订单，设置状态为准备；如果是编辑，保持原状态
            if (!purchaseOrderId || purchaseOrderId == '') {
                data.field.docStatus = '10'; // 新建订单设为准备状态
            } else {
                // 编辑订单时，如果当前状态>=30且不是驳回状态，不允许保存
                if (parseInt(orderStatus) >= 30 && parseInt(orderStatus) != 11) {
                    $.common.showErrorMessage('订单已提交，不能修改');
                    return false;
                }
                // 如果是驳回状态，修改后状态变为15
                if (parseInt(orderStatus) == 11) {
                    data.field.docStatus = '15'; // 修改状态
                } else {
                    // 保持原状态
                    data.field.docStatus = orderStatus;
                }
            }
            
            let url = "/purchaseOrder/saveOrUpdate"
            let callback = {
                onSuccess: function (result) {
                    if (result.code == '0') {
                        $.common.showSuccessMessage('订单保存成功');
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.location.reload();
                        parent.layer.close(iframeIndex);
                    } else {
                        $.common.showErrorMessage(result.message)
                        return false;
                    }
                }
            };
            $.xAjax(url, 'POST', JSON.stringify(data.field), callback);
            return false;
        });

        // 监听采购订单提交
        form.on('submit(submit-purchase-order)', function (data) {
            // 只有准备状态或修改状态的订单才能提交
            if (parseInt(orderStatus) >= 30 && parseInt(orderStatus) != 15) {
                $.common.showErrorMessage('订单已提交，不能重复提交');
                return false;
            }
            
            // 显示确认弹窗
            let confirmText = '确定提交订单？提交后将进入审核流程，无法再修改';
            if (parseInt(orderStatus) == 15) {
                confirmText = '确定重新提交订单？提交后将重新进入审核流程';
            }
            
            layer.confirm(confirmText, {
                btn: ['确定提交', '取消'],
                icon: 3,
                title: '提交确认'
            }, function(index) {
                // 设置状态为待审
                data.field.docStatus = '30';
                
                let url = "/purchaseOrder/saveOrUpdate"
                let callback = {
                    onSuccess: function (result) {
                        if (result.code == '0') {
                            $.common.showSuccessMessage('订单已提交，等待审核');
                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.location.reload();
                            parent.layer.close(iframeIndex);
                        } else {
                            $.common.showErrorMessage(result.message)
                            return false;
                        }
                    }
                };
                $.xAjax(url, 'POST', JSON.stringify(data.field), callback);
                layer.close(index);
            });
            return false;
        });
        let params = {};
        params.param = {"purchaseOrderId": purchaseOrderId};
        //列表
        table.render({
            elem: '#currentTableId',
            url: '/purchaseOrderDetail/pagesDetail',
            toolbar: '#toolbarDemo',
            method: "post",
            request: {
                pageName: "pageNum",
                limitName: "pageSize"
            },
            contentType: "application/json; charset=utf-8",
            where: params,
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'purchaseOrderDetailId', width: 65, title: 'ID', sort: true},
                {field: 'prodName', width: 120, title: '产品名称'},
                {field: 'prodNo', width: 120, title: '产品编号'},
                {field: 'quantity', width: 100, title: '数量'},
                {field: 'unit', width: 80, title: '单位'},
                {field: 'unitPrice', width: 100, title: '单价'},
                {field: 'taxFreeUnitPrice', width: 120, title: '不含税单价'},
                {field: 'taxRate', width: 80, title: '税率'},
                {field: 'taxAmount', width: 120, title: '增值税金额'},
                {field: 'totalAmount', width: 120, title: '金额'},
                {field: 'deliveryDate', width: 120, title: '交货日期', templet: "<div>{{layui.util.toDateString(d.deliveryDate, 'yyyy-MM-dd')}}</div>"},
                {field: 'deliveryLocation', width: 150, title: '交货地点'},
                {
                    field: 'createTime',
                    width: 120,
                    title: '创建时间',
                    templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'creatorId', width: 100, title: '创建人'},
                {
                    field: 'updateTime',
                    width: 120,
                    title: '修改时间',
                    templet: "<div>{{layui.util.toDateString(d.updateTime, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'update', title: '操作', minWidth: 170, toolbar: '#currentTableBar', align: "center", fixed: 'right'}
            ]],
            done: function (res, curr, count) {  //隐藏列
                if ($.common.userIsAdmin()) {
                    $("[data-field='creatorId']").css('display', 'none');
                    $("[data-field='updateTime']").css('display', 'none');
                }
                if(isShow){
                    $('.layui-btn:not(.isShow)').detach();
                }
            },
            limits: [5, 10, 15, 20, 25, 50, 100, 500],
            limit: 10,
            page: true
        });
        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                if (!purchaseOrderId || purchaseOrderId == '') {
                    $.common.showErrorMessage('请先保存采购订单');
                    return false;
                }
                var index = layer.open({
                    title: '添加采购订单明细',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/detail_add.html?purchaseOrderId=' + purchaseOrderId,
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
            }
        });

        //监听
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'show') {

                var index = layer.open({
                    title: '查看采购订单明细',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/detail_add.html?purchaseOrderId=' + purchaseOrderId
                        + '&prodId=' + data.prodId + '&supId=' + data.supId+"&isShow=true",
                    data: data,
                    success: function (index, layero) {
                        var body = layer.getChildFrame('body', layero);
                        for (let key in data) {
                            body.find("#" + key).val(data[key]);
                        }
                    },
                    end: function () {

                    }
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'edit') {

                var index = layer.open({
                    title: '修改采购订单明细',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/detail_add.html?purchaseOrderId=' + purchaseOrderId
                        + '&prodId=' + data.prodId + '&supId=' + data.supId,
                    data: data,
                    success: function (index, layero) {
                        var body = layer.getChildFrame('body', layero);
                        for (let key in data) {
                            body.find("#" + key).val(data[key]);
                        }
                    },
                    end: function () {

                    }
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除？', function (index) {
                    let url = "/purchaseOrderDetail/delete/" + obj.data.purchaseOrderDetailId;
                    let callback = {
                        onSuccess: function (result) {
                            if (result.code == 0) {
                                window.location.reload();
                            } else {
                                $.common.showErrorMessage(result.message)
                                return false;
                            }
                        }
                    };
                    $.xAjax(url, 'POST', JSON.stringify(data.field), callback);
                });
            }
        });
    });

</script>
</body>
</html>